package stream;

import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * java7和java8实现对数据的处理
 * @author 10843
 */
public class Java7 {


    public List<String> beforeJava7(List<Dish> dishList){

        List<Dish> lowCaloricDishes = new ArrayList<>();
        // 1.筛选出卡路里小于400的数据
        for (Dish dish : dishList) {
            if(dish.getCalories()>400){
                lowCaloricDishes.add(dish);
            }
        }
        // 2.对筛选出来的菜肴进行排序
        Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
            @Override
            public int compare(Dish o1, Dish o2) {
                return Integer.compare(o1.getCalories(),o2.getCalories());
            }
        });

        // 3.获取排序后菜肴的名字
        List<String> lowCaloricDishesNames = new ArrayList<>();
        for (Dish lowCaloricDishesName : lowCaloricDishes) {
            lowCaloricDishesNames.add(lowCaloricDishesName.getName());
        }
        return lowCaloricDishesNames;
    }

    public List<String> afterJava8(List<Dish> dishLish){
        return dishLish.stream()
                .filter(dish -> dish.getCalories()<400) //筛选出卡路里小于400的菜肴
                .sorted(Comparator.comparing(Dish::getCalories)) //根据卡路里进行排序
                .map(Dish::getName) //提出菜肴名字
                .collect(Collectors.toList()); //转换为list集合
    }


    /**
     * 对数据库查询到的菜肴根据菜肴种类进行分类，返回一个 Map<Type, List> 的结果
     */
    public static Map<Type,List<Dish>> afterJDK8(List<Dish> dishList){
        return dishList.stream().collect(groupingBy(Dish::getType));
    }




}
